package com.hongning.railway.ui.main.fragments.college.exam;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.hongning.railway.R;
import com.hongning.railway.app.AppViewModelFactory;
import com.hongning.railway.app.Constant;
import com.hongning.railway.databinding.FragmentExamdetailBinding;
import com.hongning.railway.entity.resbean.ResExamItem;
import com.hongning.railway.ui.adapter.AnswerAdapter;
import com.hongning.railway.util.TimeUtils;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.BR;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;

/**
 * Author: zhangjing
 * DATA:2019-08-16 18:49
 * DESC:
 * email:zhangjingworkmol@163.com
 */
public class ExamDetailFragment extends BaseFragment<FragmentExamdetailBinding,ExamDetailFragmentViewModel> {
    private ResExamItem resExamItem;
    Disposable timedisposable;
    int examtime=0;
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_examdetail;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public ExamDetailFragmentViewModel initViewModel() {
        AppViewModelFactory appViewModelFactory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this,appViewModelFactory).get(ExamDetailFragmentViewModel.class);
    }

    @Override
    public void initParam() {
        super.initParam();
        resExamItem = getArguments().getParcelable(Constant.EXTRA_DATA);
    }

    @Override
    public void initData() {
        super.initData();
        binding.includeTitle.ivLeft.setVisibility(View.VISIBLE);
        binding.includeTitle.ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        AnswerAdapter answerAdapter = new AnswerAdapter();
        answerAdapter.setViewModel(viewModel);
        binding.rvContent.setAdapter(answerAdapter);
        binding.includeTitle.tvRight.setVisibility(View.VISIBLE);
        binding.includeTitle.tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.checkAnswer();
            }
        });
        binding.rvContent.setOnTouchListener(new View.OnTouchListener() {
            private static final int MAX_CLICK_DURATION = 200;
            private long startClickTime;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        startClickTime = Calendar.getInstance().getTimeInMillis();
                        break;
                    }
                    case MotionEvent.ACTION_UP: {
                        long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                        if(clickDuration < MAX_CLICK_DURATION) {
                            return false;
                        }
                    }
                }
                return true;
            }
        });
        if (resExamItem!=null&&resExamItem.getType()==1){
            binding.includeTitle.tvTopTitle.setText("专项答题");
        }else {
            binding.includeTitle.tvTopTitle.setText("每周答题");
        }
        PagerSnapHelper pagerSnapHelper=new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(binding.rvContent);
        viewModel.loadExamData(resExamItem.getId()+"");
        initTimer();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uiSubmitButtonState.submitdialog.observe(this, new Observer<ExamDetailFragmentViewModel.SubmitButtonState>() {
            @Override
            public void onChanged(@Nullable ExamDetailFragmentViewModel.SubmitButtonState submitButtonState) {
                showDialog(submitButtonState.title,submitButtonState.content);
            }
        });
    }
    private void initTimer(){
        if (resExamItem.getAnswerTime()>=60){
            binding.tvTime.setText("剩余时间："+TimeUtils.getFormatTimeHHMM(resExamItem.getAnswerTime()*60*1000L,"HH:mm:ss"));
        }else {
            binding.tvTime.setText("剩余时间："+ TimeUtils.getFormatTimeHHMM(resExamItem.getAnswerTime()*60*1000L,"mm:ss"));
        }
        timedisposable= Observable.interval(1, TimeUnit.SECONDS)
                .compose(RxUtils.schedulersTransformer())
                .compose(this.bindToLifecycle())
                .subscribe((Consumer<Long>) along -> {
                    String time;
                    if (resExamItem.getAnswerTime()>60){
                        time =  TimeUtils.getFormatTimeHHMM((resExamItem.getAnswerTime()*60-along)*1000L,"HH:mm:ss");
                    }else {
                        time =  TimeUtils.getFormatTimeHHMM((resExamItem.getAnswerTime()*60-along)*1000L,"mm:ss");
                    }
                   binding.tvTime.setText("剩余时间："+time);
                    examtime=along.intValue();
                   if (resExamItem.getAnswerTime()*60-along<=0){
                       showDialog("考试超时","提交试题将完成考试，获得积分。不提交则视为重新考试，不记录考试选项。");
                       if (timedisposable!=null){
                           timedisposable.dispose();
                       }
                   }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });

    }

    private void showDialog(String title,CharSequence content){
        String nagativeStr = "取消";
        String positiveStr = "确定";
        if (title.equals("考试超时")){
            nagativeStr = "不提交";
            positiveStr = "提交";
        }
        MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
                .title(title)
                .titleGravity(GravityEnum.CENTER)
                .contentGravity(GravityEnum.CENTER)
                .negativeText(nagativeStr)
                .negativeColor(getResources().getColor(R.color.text66))
                .positiveText(positiveStr)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (title.equals("考试超时")){
                            getActivity().finish();
                        }else {
                            dialog.dismiss();
                        }

                    }
                }).onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        viewModel.submitAnswer(resExamItem.getId()+"",TimeUtils.getFormatMiniteAndSecString(examtime));
                    }
                })
                .content(content)
                .build();
        dialog.show();
    }
}
